package com.zens.cms.controller;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zens.cms.binlder.procedure;
import com.zens.cms.entity.TColumn;
import com.zens.cms.services.ITColumn;

import java.math.BigDecimal;

/**
 * 鏍忕洰淇℃伅
 * @author wangzhaowei(wangzw@evmtv.com)
 * @time 2013-1-18 涓婂崍02:24:40
 */
@Controller
public class TColumnInterfaceContolller {
	
	@Resource
	ITColumn iTColumn;
	

	@RequestMapping("/queryPreviousColumn")
	public String queryPreviousColumn(Model model,String id){
		if(id!="")
		{
			Long ID = Long.parseLong(id);
			JSONObject json = new JSONObject();
			int Length = 0;
			try
			{
				List<TColumn>  col = iTColumn.queryPreColumn(ID);
				
				//List<TColumn> list = new ArrayList();
				List<String> list = new ArrayList();
				
				for(TColumn tcolumn:col){
					//list.add(tcolumn);
					//list.add(tcolumn.getFcolumnname());
					Length = tcolumn.getFcolumnlevel();
					if(tcolumn.getFcolumnlevel()>1)
					{
						list.add(tcolumn.getFcolumnname());
						boolean SYS = true;
						Long select_id = tcolumn.getId();
						while(SYS)
						{
							
								List<TColumn>  coll = iTColumn.queryPreColumn(select_id);
								for(TColumn tcolumn_:coll){
									list.add(tcolumn_.getFcolumnname());
									select_id = tcolumn_.getId();
									if(tcolumn_.getFcolumnlevel()==1)
									{
										SYS = false;
									}
								}
								
							
						}
					
					}
					if(tcolumn.getFcolumnlevel()==1)
					{
					    Length = 0;    
					}
				json.put("result", "success");
				json.put("length", Length);
				json.put("columnname", list);
				model.addAttribute("result", json.toString());
				}
			}catch(Exception e)
			{
				json.put("result","failed");
				json.put("length", Length);
				model.addAttribute("result", json.toString());
			}
			
		}
		return "/json";
	}
	@RequestMapping("/formatColumnTree")
	public String formatColumnTree(Model model,String FSiteID)
	{
		Long ID = Long.parseLong(FSiteID);
		procedure pro = new procedure();
		pro.callIn(ID);
		model.addAttribute("result", "format Tree=>WebID:"+ID);
		return "/json";
	}
	//璁＄畻鐢ㄦ椂
	public String getEsapletime(long starttime)
	{
		long endtime = System.currentTimeMillis();
		return getDecimal(endtime-starttime,1000);
	}
	public String getDecimal(long divisor,long dividend)
	{
		 // 闄ゆ暟
		  BigDecimal bd = new BigDecimal(divisor);
		  // 琚櫎锟�
		  BigDecimal bd2 = new BigDecimal(dividend);
		  // 杩涜闄ゆ硶杩愮畻,淇濈暀200浣嶅皬锟�鏈綅浣跨敤鍥涜垗浜斿叆鏂瑰紡,杩斿洖缁撴灉
		  BigDecimal result = bd.divide(bd2, 200, BigDecimal.ROUND_HALF_DOWN);
		  // 鎸囧畾鎯宠鐨勫皬鏁颁綅闀垮害鍙栵拷?
		  NumberFormat nf = NumberFormat.getNumberInstance();
		  nf.setMaximumFractionDigits(20);// 锟�锟斤拷灏忔暟锟�
		  nf.setMinimumFractionDigits(3); // 锟�锟斤拷灏忔暟锟�
		  String str = nf.format(result);
		  return str;
	}
	//鍒ゆ柇瀛楃涓叉槸鍚﹀瓨鍦ㄤ簬鏁扮粍锟�
	public boolean getIsmatch(String[] match , String str)
	{
		boolean a = false;
		  for(int i=0;i<match.length;i++)
		  {
		   if(match[i].matches(str))
		   {
		    a =  true;
		    break;
		   }
		   else
		   {a = false;}
            
		 }
		  return a;
	}
	//棣栧瓧姣嶈浆灏忓啓
    public static String toLowerCaseFirstOne(String s)
    {
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }
    //棣栧瓧姣嶈浆澶у啓
    public static String toUpperCaseFirstOne(String s)
    {
        if(Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }
	@RequestMapping("/getColumn")
	public String getColumn(Model model,HttpServletRequest request)
	{
		long starttime = System.currentTimeMillis();
		JSONObject json;
		String version = "1.0";
		String jsonStr = "";
		String param = request.getParameter("param");
		String key[]= {"ID","FSiteID","FTemplateGUID","FColumnName","FColumnLevel","FColumnGp","FColumnUrl","FSortNum","FChecked"};
		
		//--------------------------------------璇锋眰鍙傛暟鎺ユ敹澶勭悊---------------------------------------------//
		if(param==null)
		{
			String time = getEsapletime(starttime);
			jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'400',msg:'鏈兘鎺ユ敹鍒拌姹傚弬鏁癧param]',data:[]}";
			model.addAttribute("result", jsonStr);
			return "/json";
		}
		//--------------------------------------璇锋眰鍙傛暟鏍煎紡澶勭悊---------------------------------------------//
		try
		{
			json = JSONObject.fromObject(param);
		}catch(Exception ex)
		{
			String time = getEsapletime(starttime);
			jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'410',msg:'鍙戯拷?鍙傛暟鏍煎紡閿欒',data:[]}";
			model.addAttribute("result", jsonStr);
			return "/json";
		}
		
		
		//---------------------------------------璇锋眰鍙傛暟澶勭悊------------------------------------------------//
		//鑾峰彇璇锋眰鍙傛暟鍙婂弬鏁扮被寮傚父
		String queryBy = json.get("queryBy").toString();
		if(!queryBy.matches("siteId")&&!queryBy.matches("columnId"))
		{
			String time = getEsapletime(starttime);
			jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'448',msg:'鍙傛暟鍚峓"+queryBy+"]涓嶆锟�,data:[]}";
			model.addAttribute("result", jsonStr);
			return "/json";
        }
		String siteId = queryBy.matches("siteId")&&!json.get("siteId").toString().matches("")?json.get("siteId").toString():"siteIdNull";
		String columnId = queryBy.matches("columnId")&&!json.get("columnId").toString().matches("")?json.get("columnId").toString():"columnIdNull";
		String depth = json.get("depth").toString().matches("")?"depthNull":json.get("depth").toString();
		String fetchField = param.contains("fetchField")?json.get("fetchField").toString():"ID,FColumnName,FColumnLevel";
		if(queryBy.matches("siteId")&&siteId.matches("siteIdNull"))
		{
			String time = getEsapletime(starttime);
			jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'118',msg:'鍙傛暟["+queryBy+"]鍊间负锟�,data:[]}";
			model.addAttribute("result", jsonStr);
			return "/json";
		}
		if(queryBy.matches("columnId")&&columnId.matches("columnIdNull"))
		{
			String time = getEsapletime(starttime);
			jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'118',msg:'鍙傛暟["+queryBy+"]鍊间负锟�,data:[]}";
			model.addAttribute("result", jsonStr);
			return "/json";
		}
		
		if(depth.matches("depthNull"))
		{
			String time = getEsapletime(starttime);
			jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'118',msg:'鍙傛暟[depth]鍊间负锟�,data:[]}";
			model.addAttribute("result", jsonStr);
			return "/json";
		}
		
		String [] arr = fetchField.split("\\,");
		
		for(String x:arr)
		{
			if(!getIsmatch(key,x))
			{
				String time = getEsapletime(starttime);
				jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'447',msg:'fetchField[=>"+x+"<=]涓嶅瓨鍦ㄤ簬鏁版嵁搴撲腑',data:[]}";
				model.addAttribute("result", jsonStr);
				return "/json";
			}
		}
		
		//------------------------------------------鏌ヨ杩囩▼澶勭悊------------------------------------------------//
		if(queryBy.matches("siteId"))
		{
			TColumn tcol = new TColumn();
			tcol.setFsiteid(Long.parseLong(siteId));
			List<TColumn>  col = iTColumn.queryBySiteID(tcol);
			if(col.size()==0)
			{
				String time = getEsapletime(starttime);
				jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'201',msg:'鏌ヨ绔欑偣涓嶅瓨锟�,data:[]}";
				model.addAttribute("result", jsonStr);
				return "/json";
			}
			boolean Check_depth=false;
			int maxLevel = 0;
			for(TColumn x:col)
			{
				if(x.getFcolumnlevel()>=Integer.parseInt(depth))
				{
					Check_depth=true;
					break;
				}
				maxLevel = x.getFcolumnlevel()>maxLevel?x.getFcolumnlevel():maxLevel;
			}
			if(!Check_depth)
			{
				String time = getEsapletime(starttime);
				jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'202',msg:'鏌ヨ娣卞害瓒呭嚭鍙缃煡璇㈡繁搴︽渶澶э拷?=>['"+maxLevel+"']',data:[]}";
				model.addAttribute("result", jsonStr);
				return "/json";
			}
			else
			{
				
				String [] element = fetchField.split("\\,");
				String [] select_element = new String[element.length];
				for(int ii=0;ii<element.length;ii++)
				{
					select_element[ii] = toUpperCaseFirstOne(element[ii].toLowerCase());
					    
				}
				
				TColumn scol = new TColumn();
				scol.setFsiteid(Long.parseLong(siteId));
				scol.setFcolumnlevel(Integer.parseInt(depth));
				List<TColumn>  cols = iTColumn.queryBySiteIDandLevel(scol);
				List<Map> list_Site=new ArrayList();
				
				for(int snum = 0;snum<cols.size();snum++)
				{
					Map<String, String> map = new HashMap<String, String>();
					map.put("Id", cols.get(snum).getId().toString());
					map.put("Fsiteid", cols.get(snum).getFsiteid().toString());
					map.put("Ftemplateguid", cols.get(snum).getFtemplateguid().toString());
					map.put("Fcolumnname", cols.get(snum).getFcolumnname().toString());
					map.put("Fcolumnlevel", cols.get(snum).getFcolumnlevel().toString());
					map.put("Fcolumngp", cols.get(snum).getFcolumngp().toString());
					map.put("Fcolumnurl", cols.get(snum).getFcolumnurl().toString());
					map.put("Fsortnum", cols.get(snum).getFsortnum().toString());
					map.put("Fchecked", cols.get(snum).getFchecked().toString());
					list_Site.add(map);
					//map.clear();
				}
				
				StringBuffer siteColumn_buffer = new  StringBuffer("[");
				for(int j = 0;j<cols.size();j++)
				{
					//JSONObject鏃犲簭 寮冪敤
					//JSONObject json_Str = new JSONObject();
					if(list_Site.get(j).get("Fchecked").toString().matches("1"))
					{
						siteColumn_buffer.append("{");
						for(int jj = 0; jj<select_element.length;jj++)
						{
							siteColumn_buffer.append(element[jj]);
							siteColumn_buffer.append(":");
							siteColumn_buffer.append("'");
							siteColumn_buffer.append(list_Site.get(j).get(select_element[jj]));
							siteColumn_buffer.append("'"); 
						    siteColumn_buffer.append(",");
						   
							//json_Str.put(select_element[jj], list_Site.get(j).get(select_element[jj]));
						}
						siteColumn_buffer.append("extData:{}");
						siteColumn_buffer.append("},");
						//json_Str.put("extData","{}");
						//siteColumn_buffer.append(json_Str.toString()+",");
					}
				}
				String data_Str = siteColumn_buffer.toString();
				if(data_Str!= null&&data_Str!= null&&data_Str.substring(data_Str.length()-1,data_Str.length()).matches(",")){
					data_Str = data_Str.substring(0,data_Str.length()-1);
	            }
				data_Str = data_Str+"]";
				String time = getEsapletime(starttime);
				data_Str = "{success:'1',version:'"+version+"',queryElapsed:'"+time+"',errCode:'',msg:'',data:"+data_Str+"}";
				model.addAttribute("result", data_Str);
				return "/json";
			}


		}
		if(queryBy.matches("columnId"))
		{
			TColumn tcol = iTColumn.query(Long.parseLong(columnId));
			if(tcol==null)
			{
				String time = getEsapletime(starttime);
				jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'200',msg:'鏌ヨ鏍忕洰涓嶅瓨锟�,data:[]}";
				model.addAttribute("result", jsonStr);
				return "/json";
			}
			List<TColumn> ltcol = iTColumn.querybyFColumnLevel(tcol);
			boolean LastNode = false;
			if(ltcol.size()==1)
			{
				ltcol = iTColumn.querybyFColumnLevelToLastOne(tcol);
				LastNode = true;
			}
			if(depth.matches("0"))
			{
				String time = getEsapletime(starttime);
				jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'199',msg:'鏌ヨ鏍忕洰娣卞害锟�',data:[]}";
				model.addAttribute("result", jsonStr);
				return "/json";
			}
			int target_level = tcol.getFcolumnlevel()+Integer.parseInt(depth)-1;
			if(tcol==null)
			{
				String time = getEsapletime(starttime);
				jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'203',msg:'鏌ヨ鏍忕洰涓嶅瓨锟�,data:[]}";
				model.addAttribute("result", jsonStr);
				return "/json";
			}
			//List<TColumn> col = iTColumn.querybyFsortNum(tcol);
			String [] element = fetchField.split("\\,");
			String [] select_element = new String[element.length];
			for(int ii=0;ii<element.length;ii++)
			{
				select_element[ii] = toUpperCaseFirstOne(element[ii].toLowerCase());
				    
			}
			List<TColumn> cols = iTColumn.querybyFsortNum(tcol,ltcol.get(0).getFsortnum());
			int length = cols.size();
			
			if(ltcol.size()>1)
			{				
				cols = iTColumn.querybyFsortNum(tcol,ltcol.get(1).getFsortnum());
				length = cols.size()-1;
			}
			if(LastNode == true)
			{
				cols = iTColumn.querybyFsortNum(tcol,ltcol.get(ltcol.size()-1).getFsortnum());
				length = cols.size();
			}
			int maxLevel = 0;
			for(TColumn x:cols)
			{
				maxLevel = x.getFcolumnlevel()>maxLevel?x.getFcolumnlevel():maxLevel;
			}
			if(maxLevel<target_level)
			{
				int depthLevel = maxLevel - tcol.getFcolumnlevel()+1;
				String time = getEsapletime(starttime);
				jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'204',msg:'鏌ヨ鏍忕洰娣卞害瓒呭嚭璇ユ爮鐩彲璁剧疆鏌ヨ娣卞害锟�锟斤拷锟�>['"+depthLevel+"']',data:[]}";
				model.addAttribute("result", jsonStr);
				return "/json";
			}
			List<Map> list_Site=new ArrayList();
			
			for(int snum = 0;snum<length;snum++)
			{
				Map<String, String> map = new HashMap<String, String>();
				map.put("Id", cols.get(snum).getId().toString());
				map.put("Fsiteid", cols.get(snum).getFsiteid().toString());
				map.put("Ftemplateguid", cols.get(snum).getFtemplateguid().toString());
				map.put("Fcolumnname", cols.get(snum).getFcolumnname().toString());
				map.put("Fcolumnlevel", cols.get(snum).getFcolumnlevel().toString());
				map.put("Fcolumngp", cols.get(snum).getFcolumngp().toString());
				map.put("Fcolumnurl", cols.get(snum).getFcolumnurl().toString());
				map.put("Fsortnum", cols.get(snum).getFsortnum().toString());
				map.put("Fchecked", cols.get(snum).getFchecked().toString());
				list_Site.add(map);
				//map.clear();
			}
			
			StringBuffer siteColumn_buffer = new  StringBuffer("[");
			for(int j = 0;j<length;j++)
			{
				if(cols.get(j).getFcolumnlevel()<=target_level)
				{
						//JSONObject鏃犲簭 寮冪敤
						//JSONObject json_Str = new JSONObject();
					if(list_Site.get(j).get("Fchecked").toString().matches("1"))
					{
						siteColumn_buffer.append("{");
						for(int jj = 0; jj<select_element.length;jj++)
						{
								
							siteColumn_buffer.append(element[jj]);
							siteColumn_buffer.append(":");
							siteColumn_buffer.append("'");
							siteColumn_buffer.append(list_Site.get(j).get(select_element[jj]));
							siteColumn_buffer.append("'"); 
						    siteColumn_buffer.append(",");
						   
							//json_Str.put(select_element[jj], list_Site.get(j).get(select_element[jj]));
						}
						siteColumn_buffer.append("extData:{}");
						siteColumn_buffer.append("},");
					}
				}
			}
			String data_Str = siteColumn_buffer.toString();
			if(data_Str!= null&&data_Str.substring(data_Str.length()-1,data_Str.length()).matches(",")){
				data_Str = data_Str.substring(0,data_Str.length()-1);
            }
			data_Str = data_Str+"]";
			String time = getEsapletime(starttime);
			data_Str = "{success:'1',version:'"+version+"',queryElapsed:'"+time+"',errCode:'',msg:'',data:"+data_Str+"}";
			model.addAttribute("result", data_Str);
			return "/json";
				
			
			
			/*
			boolean Check_depth=false;
			int maxLevel = 0;
			for(TColumn x:col)
			{
				if(x.getFcolumnlevel()>=Integer.parseInt(depth))
				{
					Check_depth=true;
					break;
				}
				maxLevel = x.getFcolumnlevel()>maxLevel?x.getFcolumnlevel():maxLevel;
			}
			if(!Check_depth)
			{
				String time = getEsapletime(starttime);
				jsonStr = "{success:'0',version:'"+version+"',queryElapsed:'"+time+"',errCode:'202',msg:'鏌ヨ娣卞害瓒婄晫瓒呭嚭瀛樺湪灞傜骇锟�锟斤拷锟�>['"+maxLevel+"']',data:[]}";
				model.addAttribute("result", jsonStr);
				return "/json";
			}
			else
			{
				
				String [] element = fetchField.split("\\,");
				String [] select_element = new String[element.length];
				for(int ii=0;ii<element.length;ii++)
				{
					select_element[ii] = toUpperCaseFirstOne(element[ii].toLowerCase());
					    
				}
				
				TColumn scol = new TColumn();
				scol.setFsiteid(Long.parseLong(siteId));
				scol.setFcolumnlevel(Integer.parseInt(depth));
				List<TColumn>  cols = iTColumn.queryBySiteIDandLevel(scol);
				List<Map> list_Site=new ArrayList();
				
				for(int snum = 0;snum<cols.size();snum++)
				{
					Map<String, String> map = new HashMap<String, String>();
					map.put("Id", cols.get(snum).getId().toString());
					map.put("Fsiteid", cols.get(snum).getFsiteid().toString());
					map.put("Ftemplateguid", cols.get(snum).getFtemplateguid().toString());
					map.put("Fcolumnname", cols.get(snum).getFcolumnname().toString());
					map.put("Fcolumnlevel", cols.get(snum).getFcolumnlevel().toString());
					map.put("Fcolumngp", cols.get(snum).getFcolumngp().toString());
					map.put("Fcolumnurl", cols.get(snum).getFcolumnurl().toString());
					map.put("Fsortnum", cols.get(snum).getFsortnum().toString());
					map.put("Fchecked", cols.get(snum).getFchecked().toString());
					list_Site.add(map);
					//map.clear();
				}
				
				StringBuffer siteColumn_buffer = new  StringBuffer("[");
				for(int j = 0;j<cols.size();j++)
				{
					//JSONObject鏃犲簭 寮冪敤
					//JSONObject json_Str = new JSONObject();
					siteColumn_buffer.append("{");
					for(int jj = 0; jj<select_element.length;jj++)
					{
						siteColumn_buffer.append(element[jj]);
						siteColumn_buffer.append(":");
						siteColumn_buffer.append("'");
						siteColumn_buffer.append(list_Site.get(j).get(select_element[jj]));
						siteColumn_buffer.append("'"); 
					    siteColumn_buffer.append(",");
					   
						//json_Str.put(select_element[jj], list_Site.get(j).get(select_element[jj]));
					}
					siteColumn_buffer.append("extData:{}");
					siteColumn_buffer.append("},");
					//json_Str.put("extData","{}");
					//siteColumn_buffer.append(json_Str.toString()+",");
				}
				String data_Str = siteColumn_buffer.toString();
				if(data_Str!= null){
					data_Str = data_Str.substring(0,data_Str.length()-1);
	            }
				data_Str = data_Str+"]";
				String time = getEsapletime(starttime);
				data_Str = "{success:'1',version:'"+version+"',queryElapsed:'"+time+"',errCode:'',msg:'',data:"+data_Str+"}";
				model.addAttribute("result", data_Str);
				return "/json";
			}

         */
		}
		model.addAttribute("result", fetchField);
		return "/json";
	}
}
